package com.kovalko.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;

import java.util.*;

/**
 * Created by 4uvak on 08.07.2014.
 */
public class ComparisonPage extends BasePage {

    private static final By KEY_LOCATOR = By.xpath("//td[@class = 'detail-title']");
    private static final String VALUE_LOCATOR = "//td[@class='detail-title']/ancestor::tr/td[%d]";

    private static final String COMPARISON_PAGE_TEMPLATE = "http://bt.rozetka.com.ua/bigbt/refrigerators/comparison/ids=";
    private static final String ONLY_DIFFERENCE = "Только отличия";

    public ComparisonPage(WebDriver driver, String caseCode1, String caseCode2) {
        super(driver, COMPARISON_PAGE_TEMPLATE + caseCode1 + "," + caseCode2);
    }

    public Map<String, String> productCharacteristics(int column) {
        Map<String, String> goodParameters = new LinkedHashMap<>();
        List<String> keys = getParameters();
        List<WebElement> values = driver.findElements(By.xpath(String.format(VALUE_LOCATOR, column)));
        Assert.assertEquals(keys.size(), values.size(), "different number of keys and values");
        for (int j = 0; j < keys.size(); j++) {
            goodParameters.put(keys.get(j), values.get(j).getText());
        }
        return goodParameters;
    }

    public List<String> getParameters() {
        List<String> result = new ArrayList<>();
        List<WebElement> elements = driver.findElements(KEY_LOCATOR);
        for (WebElement element : elements) {
            if (!"".equals(element.getText().trim()))
                result.add(element.getText());
        }
        return result;
    }

    public Set<String> calculateParametersThatDiffer() {
        return calculateDifferentKeys(productCharacteristics(2), productCharacteristics(3));
    }

    private Set<String> calculateDifferentKeys(Map<String, String> goodCharacteristics1, Map<String, String> goodCharacteristics2) {
        Set<String> difference = new LinkedHashSet<>();
        Assert.assertEquals(goodCharacteristics1.size(), goodCharacteristics2.size(), "different number of characteristics");
        for (String key : goodCharacteristics1.keySet()) {
            if (!goodCharacteristics1.get(key).equals(goodCharacteristics2.get(key))){
                difference.add(key);
            }
        }
        return difference;
    }

    public void clickOnlyDifferentButton(){
        driver.findElement(By.partialLinkText(ONLY_DIFFERENCE)).click();
    }


}
